/* eslint-disable */
import React, { Component } from 'react';
import "./App.scss";
import { connect } from "react-redux";
import { bindActionCreators } from 'redux';
import * as actions from './../actions/index';
import { withRouter } from "react-router-dom";
import {API_BASE_URL,WS_API_URL} from "./../urlConfig/index";
import { getEmpData,regionList,getStoreInfo,getEmpDataForSet} from "./../api/indexApi";


class App extends Component {
  constructor(props) {
    super(props);     
    this.state = { error: false ,storeId:"",count:0,nowStatus:true,callAlertList:[],isAlertInfo:false,allAudioOptions:[],empList:[]};
    this.connect = this.connect.bind(this);
    this.topWindow = this.topWindow.bind(this);
    this.refreshWindow = this.refreshWindow.bind(this);
    this.closeAlert = this.closeAlert.bind(this);
    this.createAudio = this.createAudio.bind(this);
    this.getAudioDevices = this.getAudioDevices.bind(this);
    this.getIpArrInfo = this.getIpArrInfo.bind(this);
    this.playVoice = this.playVoice.bind(this);
    this.generateNumVoice = this.generateNumVoice.bind(this);
    this.convertCurrency = this.convertCurrency.bind(this);
    this.createCallEmp = this.createCallEmp.bind(this);
  }
  render() {
    let {callAlertList,isAlertInfo} = this.state;
    return (
      <div className="App">
        {this.props.children}
        <div className="refresh-top">
            {/* <span className="iconfont icon-zhiding" onClick={()=>this.playVoice(['119'])}></span> */}
            <span className="iconfont icon-zhiding" onClick={()=>this.topWindow()}></span>
            <span className="iconfont icon-shuaxin" onClick={()=>this.refreshWindow()}></span>
        </div>
        {
            callAlertList.length>0&&isAlertInfo?(
                <div className="alert-wrap">
                    <div className="alert-wrap-list">
                        {
                            callAlertList.map((item,index)=>{
                                return(
                                    <div className="list-item" key={index}>
                                        <span className="alert-info">{item.info}</span>
                                        <span className="close-btn">
                                            <i className="iconfont iconguanbi" onClick={()=>this.closeAlert(item,index)}></i>
                                        </span>
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
            ):("")
        }
      </div>
    );
  }
  closeAlert(item,index){
    let callAlertList = this.state.callAlertList;
    callAlertList.splice(index,1);
    console.log(callAlertList);
    this.setState({
        callAlertList
    });
  }
  refreshWindow(){
    window.location.reload(true);
  }
  topWindow(){
    $(".cont").animate({ scrollTop: 0 }, 500);
  }
  getAudioDevices() {
    navigator.mediaDevices.enumerateDevices().then(res => {
        const audioDevices = res.filter((device) => device.kind === "audiooutput");
        console.log("navigator.mediaDevices", audioDevices);
        this.setState({
            allAudioOptions: audioDevices,
        });
    });
}
  async componentDidMount(){
    try {
        clearInterval(this.timerForalert);
        let isAlertInfo = localStorage.getItem("isAlertInfo");
        isAlertInfo = isAlertInfo?JSON.parse(isAlertInfo):false;
        console.log(this.props)
        let searchStr = window.location.search.split('?')[1];
        let searchArr = searchStr.split('&');
        let searchObj = {};
        for (var i = 0; i < searchArr.length; i++) {
            var curParam = searchArr[i].split('=');
            searchObj[curParam[0]] = curParam[1];
        }
        this.setState({
            storeId: searchObj.storeId,
            isAlertInfo,
        });
        // if(!localStorage.getItem("storeId")){
        localStorage.setItem("storeId",searchObj.storeId);
        // }
        this.connect(searchObj.storeId);
    } catch (error) {
        console.log(error);
    }
    let res = await getEmpData(searchObj.storeId, 0, 10);
    localStorage.setItem("voiceEnabled",res.data.voiceEnabled?1:0);
    try {
        localStorage.setItem("posCallEnabled",res.data.posCallEnabled?1:0);
        localStorage.setItem("offOnVoiceNotify",res.data.offOnVoiceNotify?1:0);
    } catch (error) {
        console.log("error",error)
    }
    if(res.data.voiceEnabled){
        try {
            this.getAudioDevices();
        } catch (error) {
            console.log(error);
        }
    }
    // 下机播报语音start
    try {
        window.timer = setInterval(()=>{
            this.getIpArrInfo();
        },28*1000)
    } catch (error) {
        console.log(error);
    }
    // 下机播报语音end
    // 
    try {
        let res = await getEmpDataForSet(searchObj.storeId);
        if(res && res.data && res.data.data){
            this.setState({
                empList:res.data.data
            });
        }
        console.log("empRes",res)
    } catch (error) {
        console.log("error",error);
    }
    // 
  }
  componentWillUnmount(){
    try {
        console.log("clear window.timer")
        if(window.timer){
            clearInterval(window.timer)
        }
    } catch (error) {
        console.log(error)
    }
  }
  createCallEmp(callFirst,data){
    // start
    // let nowCallItem = data;
    // const tableNoArr = nowCallItem.tableNum.split("");
    // const empNoArr = nowCallItem.workId.split("");
    // const tempAudioArr = [];
    let nowCallItem = data;
    const tableNo = nowCallItem.tableNum;
    const empNo = nowCallItem.workId;
    const tempAudioArr = [];
    if(callFirst){
        let audioStart = `<audio style="display:none;" controls="" class="audio" src="${API_BASE_URL}v1/pos/speech?text=工作人员请注意" autoplay="autoplay" id="audios"></audio>`;
        tempAudioArr.push(
            `<audio style="display:none;" controls="" class="audio" src="${API_BASE_URL}v1/pos/speech?text=工作人员请注意" autoplay="autoplay" id="audios"></audio>`
        );
        let audios = [audioStart,...tempAudioArr,audioStart,...tempAudioArr];
        return audios;
    }else{
        let audioStart = `<audio style="display:none;" controls="" class="audio" src="${data.empUrl}" autoplay="autoplay" id="audios"></audio>`;
        let qzy = `<audio style="display:none;" controls="" class="audio" src="./cgdz/qzy.mov" autoplay="autoplay" id="audios"></audio>`;
        // 
        let tempNumbers;
        if(/^\d+$/.test(tableNoArr.join(""))){
            tempNumbers = this.convertCurrency(Number(tableNoArr.join("")));
            tempNumbers = String(tempNumbers).split("");
        }else{
            tempNumbers = tableNoArr;
        }
        tempNumbers.forEach(it=>{
            let tempAudio = `<audio style="display:none;" controls="" class="audio" src="./audio/${it}.wav" autoplay="autoplay" id="audios"></audio>`;
            tempAudioArr.push(tempAudio);
        })
        tempAudioArr.push(`<audio style="display:none;" controls="" class="audio" src="./cgdz/hjhj.mov" autoplay="autoplay" id="audios"></audio>`);
        // 
        let audios = [audioStart,qzy,audioStart,qzy,...tempAudioArr];
        return audios;
    }
    // if(callFirst){
    //     let audioStart = '<audio style="display:none;" controls="" class="audio" src="./xiaji/gzryqzy.mp3" autoplay="autoplay" id="audios"></audio>';
    //     if(tableNoArr && Array.isArray(tableNoArr)){
    //         let tempNumbers;
    //         if(/^\d+$/.test(tableNoArr.join(""))){
    //             tempNumbers = this.convertCurrency(Number(tableNoArr.join("")));
    //             tempNumbers = String(tempNumbers).split("");
    //         }else{
    //             tempNumbers = tableNoArr;
    //         }
    //         tempNumbers.forEach(it=>{
    //             let tempAudio = `<audio style="display:none;" controls="" class="audio" src="./audio/${it}.wav" autoplay="autoplay" id="audios"></audio>`;
    //             tempAudioArr.push(tempAudio);
    //         })
    //         tempAudioArr.push(`<audio style="display:none;" controls="" class="audio" src="./cgdz/hjhj.mov" autoplay="autoplay" id="audios"></audio>`);
    //         tempAudioArr.push(`<audio style="display:none;" controls="" class="audio" src="${data.empUrl}" autoplay="autoplay" id="audios"></audio>`);
    //     }
    //     let audios = [audioStart,...tempAudioArr,audioStart,...tempAudioArr];
    //     return audios;
    // }else{
    //     let audioStart = `<audio style="display:none;" controls="" class="audio" src="${data.empUrl}" autoplay="autoplay" id="audios"></audio>`;
    //     let qzy = `<audio style="display:none;" controls="" class="audio" src="./cgdz/qzy.mov" autoplay="autoplay" id="audios"></audio>`;
    //     // 
    //     let tempNumbers;
    //     if(/^\d+$/.test(tableNoArr.join(""))){
    //         tempNumbers = this.convertCurrency(Number(tableNoArr.join("")));
    //         tempNumbers = String(tempNumbers).split("");
    //     }else{
    //         tempNumbers = tableNoArr;
    //     }
    //     tempNumbers.forEach(it=>{
    //         let tempAudio = `<audio style="display:none;" controls="" class="audio" src="./audio/${it}.wav" autoplay="autoplay" id="audios"></audio>`;
    //         tempAudioArr.push(tempAudio);
    //     })
    //     tempAudioArr.push(`<audio style="display:none;" controls="" class="audio" src="./cgdz/hjhj.mov" autoplay="autoplay" id="audios"></audio>`);
    //     // 
    //     let audios = [audioStart,qzy,audioStart,qzy,...tempAudioArr];
    //     return audios;
    // }

    
    // let audioStart = '<audio style="display:none;" controls="" class="audio" src="./xiaji/gzryqzy.mp3" autoplay="autoplay" id="audios"></audio>';
    // if(tableNoArr && Array.isArray(tableNoArr) && tableNoArr.length){
    //     // 
    //     // let tempNumbers = this.convertCurrency(Number(tableNoArr.join("")));
    //     // tempNumbers = String(tempNumbers).split("");
    //     let tempNumbers = tableNoArr;
    //     // 
    //     tempNumbers.forEach(it=>{
    //         let tempAudio = `<audio style="display:none;" controls="" class="audio" src="./audio/${it}.wav" autoplay="autoplay" id="audios"></audio>`;
    //         tempAudioArr.push(tempAudio);
    //     })
    // }
    // // let audioEnd = '<audio style="display:none;" controls="" class="audio" src="./audio/呼叫_呼叫服务员.wav" autoplay="autoplay" id="audios"></audio>';
    // let audioNeed = '<audio style="display:none;" controls="" class="audio" src="./audio/号机需要.wav" autoplay="autoplay" id="audios"></audio>';
    // // 
    // const tempAudioArrForEmp = [];
    // if(empNoArr && Array.isArray(empNoArr) && empNoArr.length){
    //     // 
    //     // let tempNumbers = this.convertCurrency(Number(empNoArr.join("")));
    //     // tempNumbers = String(tempNumbers).split("");
    //     let tempNumbers = empNoArr;
    //     // 
    //     tempNumbers.forEach(it=>{
    //         let tempAudio = `<audio style="display:none;" controls="" class="audio" src="./audio/${it}.wav" autoplay="autoplay" id="audios"></audio>`;
    //         tempAudioArrForEmp.push(tempAudio);
    //     })
    // }
    // //
    // let audioBeforeEnd = '<audio style="display:none;" controls="" class="audio" src="./audio/号.wav" autoplay="autoplay" id="audios"></audio>';
    // let audioEnd = '<audio style="display:none;" controls="" class="audio" src="./audio/服务员帮助.wav" autoplay="autoplay" id="audios"></audio>';
    // let audios = [audioStart,...tempAudioArr,audioNeed,...tempAudioArrForEmp,audioBeforeEnd,audioEnd];
    // console.log("audios",audios);
    // return audios;
    // end
  }
  async getIpArrInfo(){
    if(!this.state.storeId){
        return;
    }
    const res = await regionList(this.state.storeId);
    console.log("res",res);
    let ipObj = {};
    if(res && res.hasOwnProperty("data") && res.data && Array.isArray(res.data) && res.data.length){
        res.data.forEach(it=>{
            if(it.nums && Array.isArray(it.nums) && it.nums.length){
                it.nums.forEach(ite=>{
                    let ipSplitArr = ite.ipAddress.split(".");
                    ipObj[
                        `${ipSplitArr[0]}.${ipSplitArr[1]}.${ipSplitArr[2]}.`
                    ] = [];
                })
            }
        })
        res.data.forEach(it=>{
            if(it.nums && Array.isArray(it.nums) && it.nums.length){
                it.nums.forEach(ite=>{
                    for(let k in ipObj){
                        if(ite.ipAddress.indexOf(k)!=-1){
                            ipObj[k].push({
                                ip:ite.ipAddress,
                                id:ite.id,
                                name:ite.name,
                                status:ite.status,
                                lastTime:ite.lastTime,
                                updateTime:ite.updateTime,
                                regionId:it.id
                            });
                        }
                    }
                })
            }
        })
    }
    console.log("ipObj",ipObj);
    let busyNums = [];
    let freeNums = [];
    let busyNumIds = [];
    let freeNumIds = [];
    for(let k in ipObj){
        if(ipObj[k] && Array.isArray(ipObj[k]) && ipObj[k].length){
            ipObj[k].forEach(it=>{
                if(it.status){
                    busyNums.push({
                        id:it.id,
                        name:it.name,
                        lastTime:it.lastTime,
                        updateTime:it.updateTime,
                    });
                    busyNumIds.push(it.id);
                }else{
                    if(it.status!=2){
                        freeNums.push({
                            id:it.id,
                            name:it.name,
                            lastTime:it.lastTime,
                            updateTime:it.updateTime,
                        });
                        freeNumIds.push(it.id);
                    }
                }
            })
        }
    }
    console.log("freeNums",freeNums);
    console.log("busyNums",busyNums);
    console.log("freeNumIds",freeNumIds);
    console.log("busyNumIds",busyNumIds);
    let tempBusyNums = localStorage.getItem("busyNums");
    if(tempBusyNums){
        let voiceArr = [];
        tempBusyNums = JSON.parse(tempBusyNums);
        if(tempBusyNums && Array.isArray(tempBusyNums) && tempBusyNums.length){
            tempBusyNums.forEach(it=>{
                if(busyNumIds.indexOf(it.id)==-1){
                    // voiceArr.push(it.name);
                    try {
                        freeNums.forEach(ite=>{
                            if(ite.id == it.id){
                                if(it && it.hasOwnProperty("lastTime") && (new Date(ite.lastTime).getTime() - new Date(it.lastTime).getTime()) > 8 * 1000 * 60){
                                    voiceArr.push(it.name);
                                }
                            }
                        })
                    } catch (error) {
                        voiceArr.push(it.name);
                    }
                }
            })
        }
        console.log("voiceArr",voiceArr);
        if(voiceArr.length){
            let offOnVoiceNotify = localStorage.getItem("offOnVoiceNotify");
            let posCallEnabled = localStorage.getItem("posCallEnabled");
                console.log("offOnVoiceNotify",offOnVoiceNotify)
                if((offOnVoiceNotify == true || offOnVoiceNotify == "true")){
                    this.playVoice(voiceArr);
                }
            }
        }
        localStorage.setItem("busyNums",JSON.stringify(busyNums));
    }
    // 
    convertCurrency(num) {
        const chineseNum = {
            digits: ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'],
            units: ['', '十', '百', '千'],
            bigUnits: ['', '万', '亿', '万亿']
        };

        function convertInteger(numStr) {
            if (numStr === '0') return '零';
            let result = '';
            let zeroCount = 0;
            const len = numStr.length;

            for (let i = 0; i < len; i++) {
                const digit = parseInt(numStr[i]);
                const pos = len - i - 1;
                const unitIndex = pos % 4;
                const bigUnitIndex = Math.floor(pos / 4);

                if (digit === 0) {
                    zeroCount++;
                } else {
                    if (zeroCount > 0) {
                        result += '零';
                        zeroCount = 0;
                    }
                    // 处理十位的特殊读法（例如：10读作"十"，110读作"一百一十"）
                    if (digit === 1 && unitIndex === 1 && i === 0) {
                        result += chineseNum.units[unitIndex];
                    } else {
                        result += chineseNum.digits[digit] + chineseNum.units[unitIndex];
                    }
                }

                // 添加大单位（万/亿）
                if (unitIndex === 0 && bigUnitIndex > 0) {
                    result += chineseNum.bigUnits[bigUnitIndex];
                }
            }

            return result.replace(/零+$/, '') || '零';
        }

        function convertDecimal(decimalStr) {
            return decimalStr.split('').map(c => chineseNum.digits[parseInt(c)]).join('');
        }

        // 主处理逻辑
        let numStr = typeof num === 'string' ? num : String(num);
        let isNegative = false;
        
        // 处理负数
        if (numStr.startsWith('-')) {
            isNegative = true;
            numStr = numStr.slice(1);
        }

        const [integerPart, decimalPart] = numStr.split('.');
        let result = convertInteger(integerPart || '0');

        // 处理小数部分
        if (decimalPart) {
            const isAllZero = decimalPart.split('').every(c => c === '0');
            if (!isAllZero) {
                result += '点' + convertDecimal(decimalPart);
            }
        }

        return (isNegative ? '负' : '') + result;
    }
    generateNumVoice(voiceNumbers){
        let voiceArr = [];
        if(voiceNumbers && Array.isArray(voiceNumbers)){
            voiceNumbers.forEach(it=>{
            if(it){
                let itArr = String(it).split("");
                itArr.forEach(ite=>{
                    if(/^[A-Za-z]$/.test(ite)){
                        let tempStr = String(ite).toLowerCase();
                        voiceArr.push(`<audio style="display:none" autoplay id='ipAudio' class="ipAudio" src='./audio/${tempStr}.wav'></audio>`);
                    }else{
                        voiceArr.push(`<audio style="display:none" autoplay id='ipAudio' class="ipAudio" src='./cgdz/${ite}.mov'></audio>`);
                    }
                })
                voiceArr.push(`<audio style="display:none" autoplay id='ipAudio' class="ipAudio" src='./cgdz/号机.mov'></audio>`);
            }
            })
        }
        return voiceArr;
    }
    playVoice(voiceArr){
        let flag = false;
        // $(".audio").on("playing",function () {
        //     flag = true;
        // });
        // $(".audio").on("ended",function () {
        //     flag = false;
        // });
        if(window.voiceTimer){
            clearInterval(window.voiceTimer);
        }
        // 
        // let audios = [];
      let status = true;
      let numNameStr = "";
      let computerAudios = [];
      voiceArr.forEach((it,ind)=>{
          if(ind == voiceArr.length - 1){
            computerAudios.push(
                `<audio style="display:none;" controls="" class="ipAudio" src="${API_BASE_URL}v1/pos/speech?text=${it}号机,已下机" autoplay="autoplay" id="ipAudio"></audio>`,
            );
          }else{
            computerAudios.push(
                `<audio style="display:none;" controls="" class="ipAudio" src="${API_BASE_URL}v1/pos/speech?text=${it}号机" autoplay="autoplay" id="ipAudio"></audio>`,
            );
          }
          
        //   if(/^\d+$/.test(it)){
        //     voiceArr[ind] = this.convertCurrency(Number(it));
        //   }
          // $('.index').append($('<audio style="display:none;" controls="" class="ipAudio" src="'+API_BASE_URL+'v1/pos/speech?tex=工作人员请注意,,,,,'+it+'号机已下机&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="ipAudio"></audio>')); 
          // audios.push(audio);
        //   numNameStr += `${it}号机,,,,,,,,,`;
      });
      let offOnVoiceMessage = sessionStorage.getItem("offOnVoiceMessage");
      let frontMessage = "工作人员请注意,,,,,";
      let backMessage = ",,,,,,请及时清理桌面,,,,,,保持卫生";
      if(offOnVoiceMessage && offOnVoiceMessage.indexOf("**号机已下机")!=-1){
          try {
              let message = offOnVoiceMessage.split("**号机已下机");
              if(message && Array.isArray(message) && message.length>1){
                  frontMessage = message[0];
                  backMessage = message[1];
              }
          } catch (error) {
              console.log(error);
          }
          console.log("frontMessage",frontMessage);
          console.log("backMessage",backMessage);
      }
      // let audio = `<audio style="display:none;" controls="" class="ipAudio" src="${API_BASE_URL}/v1/pos/speech?tex=${frontMessage}${numNameStr}已下机${backMessage}&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="ipAudio"></audio>`; 
      let audios = [];
      let frontMessageAudio = `<audio style="display:none;" controls="" class="ipAudio" src="./xiaji/gzryqzy.mp3" autoplay="autoplay" id="ipAudio"></audio>`; 
      let numberAudios = this.generateNumVoice(voiceArr);
      let backMessageAudio = `<audio style="display:none;" controls="" class="ipAudio" src="./xiaji/yxj.mp3" autoplay="autoplay" id="ipAudio"></audio>`; 
      audios = [frontMessageAudio,...numberAudios,backMessageAudio]
      console.log("audios",audios);
      //test start
      let startAudio = `<audio style="display:none;" controls="" class="ipAudio" src="${API_BASE_URL}v1/pos/speech?text=工作人员请注意" autoplay="autoplay" id="ipAudio"></audio>`;
      if(voiceArr && Array.isArray(voiceArr) && voiceArr.length == 1){
        audios = [
            `<audio style="display:none;" controls="" class="ipAudio" src="${API_BASE_URL}v1/pos/speech?text=工作人员请注意,,,,,${voiceArr[0]}号机已下机,,,,请及时清理桌面保持卫生&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="ipAudio"></audio>`
        ];
      }else{
        audios = [
            startAudio,
            ...computerAudios,
            `<audio style="display:none;" controls="" class="ipAudio" src="${API_BASE_URL}v1/pos/speech?text=请及时清理桌面保持卫生" autoplay="autoplay" id="ipAudio"></audio>`,
        ]
      }
      // test end
      window.voiceTimer = setInterval(()=>{
        
          let that = this;
          if(!flag){
            if(audios && Array.isArray(audios) && audios.length){
              let audioIndex = 0;
              if(!status){
                return;
              }
              status = false;//正在播放
              function playAudio(audioIndex){
                  if(audioIndex < audios.length){
                      $('.App').append(audios[audioIndex]);
                      console.log("正在播放"+audioIndex);
                      console.log('$("#ipAudio")',$(".ipAudio"))
                      let audioDeviceForOffline = "";
                        audioDeviceForOffline = localStorage.getItem("audioDevice");
                        if(audioDeviceForOffline){
                            console.log("$.ipAudio",$(".ipAudio")[0]);
                            console.log(`ipAudio is being output on ${audioDeviceForOffline}`);
                            // 
                            let deviceId = "";
                            try {
                                that.state.allAudioOptions.forEach(it=>{
                                    if(it.label == audioDeviceForOffline){
                                        deviceId = it.deviceId;
                                    }
                                })
                            } catch (error) {
                                console.log("error",error)
                            }
                            // 
                            $(".ipAudio")[0].setSinkId(deviceId);
                        }
                        // 
                      try {
                          $("#ipAudio").on("playing",function () {
                              let offlineVoiceVolum  = localStorage.getItem("offlineVoiceVolum");
                              if(offlineVoiceVolum){
                                  $(".ipAudio")[0].volume = Number(JSON.parse(offlineVoiceVolum) / 100).toFixed(2);
                              }
                          })
                      } catch (error) {
                        console.log(error)
                      }
                      try {
                        $("#ipAudio").on("ended",function () {
                            this.remove();
                            playAudio(audioIndex+1);
                        })
                      } catch (error) {
                        console.log(error)
                      }
                      
                  }else{
                      console.log("播放完毕");
                      audios = [];
                      clearInterval(window.voiceTimer);
                      status = true;
                      $("#ipAudio").remove();
                  }
              }
              playAudio(audioIndex);
            }
              // $('.index').append(audio);
              // $(".ipAudio").on("playing",function () {
              //     let offlineVoiceVolum  = localStorage.getItem("offlineVoiceVolum");
              //     if(offlineVoiceVolum){
              //         $(".ipAudio")[0].volume = Number(JSON.parse(offlineVoiceVolum) / 100).toFixed(2);
              //     }
              //     clearInterval(that.voiceTimer);
              // })
              // $(".ipAudio").on("ended",function () {
              //     this.remove();
              // })
              // 
              // if(audios && audios.length){
              //     let audioIndex = 0;
              //     function playAudio(audioIndex){
              //         if(audioIndex < audios.length){
              //             $('.index').append(audios[audioIndex]);
                          
              //             $(".ipAudio").on("playing",function () {
              //                 status = false;//正在播放
              //             })
              //             $(".ipAudio").on("ended",function () {
              //                 this.remove();
              //                 playAudio(audioIndex+1);
              //             })
              //         }else{
              //             console.log("播放完毕");
              //             clearInterval(this.voiceTimer);
              //             audios = [];
              //             status = true;
              //         }
              //     }
              //     playAudio(audioIndex);
              //     return;
              // }
          }
      },5000);
    }
  createAudio(nowCallItem){
    // start
    const tableNoArr = nowCallItem.tableNum.split("");
    const empNoArr = nowCallItem.workId.split("");
    
    let audioStart = '<audio style="display:none;" controls="" class="audio" src="./audio/工作人员请注意.wav" autoplay="autoplay" id="audios"></audio>';
    const tempAudioArr = [];
    if(tableNoArr && Array.isArray(tableNoArr) && tableNoArr.length){
        // 
        let tempNumbers;
        if(/^\d+$/.test(tableNoArr.join(""))){
            tempNumbers = this.convertCurrency(Number(tableNoArr.join("")));
            tempNumbers = String(tempNumbers).split("");
        }else{
            tempNumbers = tableNoArr;
        }
        // 
        tempNumbers.forEach(it=>{
            let tempAudio = `<audio style="display:none;" controls="" class="audio" src="./audio/${it}.wav" autoplay="autoplay" id="audios"></audio>`;
            tempAudioArr.push(tempAudio);
        })
    }
    // let audioEnd = '<audio style="display:none;" controls="" class="audio" src="./audio/呼叫_呼叫服务员.wav" autoplay="autoplay" id="audios"></audio>';
    let audioNeed = '<audio style="display:none;" controls="" class="audio" src="./audio/号机需要.wav" autoplay="autoplay" id="audios"></audio>';
    // 
    const tempAudioArrForEmp = [];
    if(empNoArr && Array.isArray(empNoArr) && empNoArr.length){
        // 
        let tempNumbers;
        if(/^\d+$/.test(empNoArr.join(""))){
            tempNumbers = this.convertCurrency(Number(empNoArr.join("")));
            tempNumbers = String(tempNumbers).split("");
        }else{
            tempNumbers = empNoArr;
        }
        // 
        tempNumbers.forEach(it=>{
            let tempAudio = `<audio style="display:none;" controls="" class="audio" src="./audio/${it}.wav" autoplay="autoplay" id="audios"></audio>`;
            tempAudioArrForEmp.push(tempAudio);
        })
    }
    //
    let audioBeforeEnd = '<audio style="display:none;" controls="" class="audio" src="./audio/号.wav" autoplay="autoplay" id="audios"></audio>';
    let audioEnd = '<audio style="display:none;" controls="" class="audio" src="./audio/服务员帮助.wav" autoplay="autoplay" id="audios"></audio>';
    let audios = [audioStart,...tempAudioArr,audioNeed,...tempAudioArrForEmp,audioBeforeEnd,audioEnd];
    console.log("audios",audios);
    return audios;
    // end
  }
  createAudioForNetManager(nowCallItem){
    const tableNoArr = nowCallItem.tableNum.split("");
    let audioStart = '<audio style="display:none;" controls="" class="audio" src="./audio/工作人员请注意.wav" autoplay="autoplay" id="audios"></audio>';
    const tempAudioArr = [];
    if(tableNoArr && Array.isArray(tableNoArr) && tableNoArr.length){
        // 
        // 
        let tempNumbers;
        if(/^\d+$/.test(tableNoArr.join(""))){
            tempNumbers = this.convertCurrency(Number(tableNoArr.join("")));
            tempNumbers = String(tempNumbers).split("");
        }else{
            tempNumbers = tableNoArr;
        }
        // 
        // 
        tempNumbers.forEach(it=>{
            let tempAudio = `<audio style="display:none;" controls="" class="audio" src="./audio/${it}.wav" autoplay="autoplay" id="audios"></audio>`;
            tempAudioArr.push(tempAudio);
        })
    }
    let audioEnd = '<audio style="display:none;" controls="" class="audio" src="./audio/呼叫_呼叫网管.wav" autoplay="autoplay" id="audios"></audio>';
    let audios = [audioStart,...tempAudioArr,audioEnd];
    return audios;
  }
  connect(storeId){
    let b = new Base64();
    let authStr = 'Basic '+ b.encode("13980547109"+':'+"123456");
    var socket = new SockJS(WS_API_URL+'gs-guide-websocket');
    this.stompClient = Stomp.over(socket);
    let that = this;
    let callList = [];
    let callAlertList = [];//用于显示弹窗信息
    // let rewardList = [];
    let status = true;
    this.stompClient.connect({'Auth-Token':authStr}, function (frame) {
        that.stompClient.ws.onerror = function ( evnt ) {
            that.connect(that.state.storeId);
        }
        that.stompClient.ws.onclose = function ( evnt ) {
            that.connect(that.state.storeId);
        }
        that.stompClient.subscribe('/message/'+storeId, async function (event) {
            console.log("我收到了服务器消息");
            let res = JSON.parse(event.body);
            // if(res.source !== "CALL" || res.source !== "REWARD"){
            //     console.log(res.source)
            //     return;
            // }
            let callType = localStorage.getItem("callType");
            if(res.source === "CALL" || res.source === "REWARD"){
                await that.setState({
                    count:that.state.count+res.count
                });
                console.log(that.state.count);
                if ( res.count > 0 ) {
                    // let audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?tex=请注意'+res.tableNum+'号呼叫'+res.workId+'服务员&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                    // $('.App').append(audio);
                    if(res.source === "CALL"){
                        
                        let info = "";
                        if(!callType || callType==="empCode"){
                            info = `请注意${res.tableNum}号呼叫${res.workId}号`;
                        }else{
                            info = `请注意${res.tableNum}号呼叫${res.empName}`;
                        }
                        let alertRes = Object.assign({isInsert:false,info},res);
                        callAlertList.push(alertRes);
                        console.log(callAlertList)
                        that.setState({
                            callAlertList
                        });
                        that.props.actions.setWsStatus({count:that.state.count});
                        clearInterval(that.timerForalert);
                        that.timerForalert = setInterval(() => {
                            callAlertList.splice(callAlertList.length-1,1);
                            that.setState({
                                callAlertList
                            });
                        }, 9000);
                    }
                    // setTimeout(()=>{
                    //     // $(".audio").remove();
                    // },9000);
                    // 员工语音包start
                    try {
                        if(res && res.empId){
                            that.state.empList.forEach(it=>{
                                if(it.id == res.empId){
                                    res.empUrl = it.empUrl;
                                }
                            })
                        }
                    } catch (error) {
                        console.log(error);
                    }
                    // 员工语音包end
                    let newRes = Object.assign({did:false},res);
                    console.log(newRes);
                    // if(callList.length > 2){
                    //     // console.log("dayue")
                    //     return;
                    // }else{
                        callList.push(newRes);
                    // }
                    console.log(callList)
                    let voiceSpeed = localStorage.getItem("voiceSpeed");
                    let sayOtherInfo = JSON.parse(localStorage.getItem("sayOtherInfo"));
                    let isAlertInfo = JSON.parse(localStorage.getItem("isAlertInfo"));
                    let isCallTwice = localStorage.getItem("isCallTwice")?JSON.parse(localStorage.getItem("isCallTwice")):false;
                    let callFirst = localStorage.getItem("callFirst")?JSON.parse(localStorage.getItem("callFirst")):false;
                    isAlertInfo = isAlertInfo?JSON.parse(isAlertInfo):false;
                    that.setState({
                        isAlertInfo
                    });
                    let audios = [];
                    function call(callList,index) {
                        if(callList.length>0 && status){
                            status = false;
                            // 默认只保留数字，如有需要则开启保留其他字符
                            if(sayOtherInfo){
                                // 识别出字母和数字
                                let tableNum = callList[index].tableNum.trim();
                                tableNum = tableNum.match(/[a-z]|\d/ig);
                                callList[index].tableNum =  tableNum.join("").toLocaleLowerCase();
                            }else{
                                let tableNum = callList[index].tableNum.match(/\d/ig);
                                callList[index].tableNum = tableNum?tableNum.join(""):"";
                            }
                            //处理工号 
                            if(callType==="empCode"){
                                if(callList[index].workId){
                                    let tempWorkId = callList[index].workId.trim();
                                    tempWorkId = tempWorkId.match(/[a-z]|\d/ig);
                                    callList[index].workId =  tempWorkId.join("").toLocaleLowerCase();
                                }
                            }
                            // 
                            // 
                            console.log(callList[index].tableNum)
                            let audio;
                            if(callList[index].source === "CALL"){
                                // if(!callType || callType==="empCode"){
                                //     audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?tex=请注意'+callList[index].tableNum+'号请注意'+callList[index].tableNum+'号呼叫'+callList[index].workId+'号&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                // }else{
                                //     audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?tex=请注意'+callList[index].tableNum+'号请注意'+callList[index].tableNum+'号呼叫'+callList[index].empName+'&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                // }
                                if(isCallTwice){
                                    if(!callType || callType==="empCode"){
                                        audios = that.createAudio(callList[index]);
                                        audios = [...audios,...audios];
                                        // end
                                        // if(callFirst){
                                        //     audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?tex=工作人员请注意,,,,,'+callList[index].tableNum+'号机呼叫'+callList[index].workId+'号服务员,工作人员请注意,,,,,'+callList[index].tableNum+'号机呼叫'+callList[index].workId+'号服务员&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                        // }else{
                                        //     audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?tex='+callList[index].workId+'号请注意,'+callList[index].workId+'号请注意,'+callList[index].tableNum+'号呼叫,'+callList[index].tableNum+'号呼叫&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                        // }
                                    }else if(callType === "netManager"){
                                        audios = that.createAudioForNetManager(callList[index]);
                                        audios = [...audios,...audios];
                                    }else{
                                        if(callFirst){
                                            // audios = that.createCallEmp(true,callList[index]);
                                            audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?text=工作人员请注意,,,,,'+callList[index].tableNum+'号机呼叫'+callList[index].empName+',工作人员请注意,,,,,'+callList[index].tableNum+'号机呼叫'+callList[index].empName+'&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                        }else{
                                            // audios = that.createCallEmp(false,callList[index]);
                                            audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?text='+callList[index].empName+'请注意,'+callList[index].empName+'请注意,'+callList[index].tableNum+'号呼叫,'+callList[index].tableNum+'号呼叫&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                        }
                                    }
                                }else{
                                    if(!callType || callType==="empCode"){
                                        audios = that.createAudio(callList[index]);
                                        // // 
                                        // if(callFirst){
                                        //     audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?tex=工作人员请注意,,,,,'+callList[index].tableNum+'号机呼叫'+callList[index].workId+'号服务员,呼叫'+callList[index].workId+'号服务员&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                        // }else{
                                        //     audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?tex='+callList[index].workId+'号请注意,'+callList[index].workId+'号请注意,'+callList[index].tableNum+'号呼叫&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                        // }
                                    }else if(callType === "netManager"){
                                        audios = that.createAudioForNetManager(callList[index]);
                                    }else{
                                        if(callFirst){
                                            audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?text=工作人员请注意,,,,,'+callList[index].tableNum+'号机呼叫'+callList[index].empName+',呼叫'+callList[index].empName+'&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                            // audios = that.createCallEmp(true,callList[index]);
                                        }else{
                                            audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?text='+callList[index].empName+'请注意,'+callList[index].empName+'请注意,'+callList[index].tableNum+'号呼叫&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                            // audios = that.createCallEmp(false,callList[index]);
                                        }
                                    } 
                                }
                                
                            }else if(callList[index].source === "REWARD"){
                                let unit;
                                switch (callList[index].productName) {
                                    case "玫瑰花":
                                    unit="朵";
                                    break;
                                    case "跑车":
                                    unit="辆";
                                    break;
                                    case "别墅":
                                    unit="栋";
                                    break;
                                    case "游艇":
                                    unit="只";
                                    break;
                                    case "水晶鞋":
                                    unit="双";
                                    break;
                                    default:
                                    unit="个";
                                    break;
                                }
                                if(!callType || callType==="empCode"){
                                    audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?text='+callList[index].tableNum+'号客户机给'+callList[index].empCode+'号打赏'+callList[index].qty+''+unit+''+callList[index].productName+'&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                }else{
                                    audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?text='+callList[index].tableNum+'号客户机给'+callList[index].empName+'打赏'+callList[index].qty+''+unit+''+callList[index].productName+'&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
                                }
                            }
                            // 
                            
                            if(audios && audios.length){
                                let audioIndex = 0;
                                function playAudio(audioIndex){
                                    if(audioIndex < audios.length){
                                        console.log(audios,"audios");
                                        // return;
                                        // 
                                        $('.App').append(audios[audioIndex]);
                                        console.log("正在播放"+audioIndex);
                                        // 
                                        // setTimeout(()=>{
                                            let audioDevice = "";
                                            audioDevice = localStorage.getItem("audioDevice");
                                            if(audioDevice){
                                                console.log("$.audio",$(".audio")[0]);
                                                console.log(`audio is being output on ${audioDevice}`);
                                                // 
                                                let deviceId = "";
                                                that.state.allAudioOptions.forEach(it=>{
                                                    if(it.label == audioDevice){
                                                        deviceId = it.deviceId;
                                                    }
                                                })
                                                // 
                                                $(".audio")[0].setSinkId(deviceId);
                                            }


                                            $(".audio").on("playing",function () {
                                                status = false;//正在播放
                                                if(!voiceSpeed){
                                                    $(".audio")[0].playbackRate = 1;
                                                }else{
                                                    $(".audio")[0].playbackRate = Number(JSON.parse(voiceSpeed) / 100).toFixed(2);
                                                }
                                                // console.log("正在播放");
                                            })
                                            $(".audio").on("ended",function () {
                                                this.remove();
                                                playAudio(audioIndex+1);
                                            })
                                        // },100);
                                        // 
                                    }else{
                                        console.log("播放完毕");
                                        audios = [];
                                        callList.splice(index,1);
                                        console.log(callList);
                                        status = true;
                                        call(callList,0);
                                    }
                                }
                                playAudio(audioIndex);
                                return;
                            }
                            // 
                            $('.App').append(audio);
                            // 
                            // setTimeout(()=>{
                                let audioDevice = "";
                                audioDevice = localStorage.getItem("audioDevice");
                                if(audioDevice){
                                    console.log("$.audio",$(".audio")[0]);
                                    console.log(`audio is being output on ${audioDevice}`);
                                    // 
                                    let deviceId = "";
                                    that.state.allAudioOptions.forEach(it=>{
                                        if(it.label == audioDevice){
                                            deviceId = it.deviceId;
                                        }
                                    })
                                    // 
                                    $(".audio")[0].setSinkId(deviceId);
                                }
                                status = false;//正在播放
                                if(!voiceSpeed){
                                    $(".audio")[0].playbackRate = 1;
                                }else{
                                    $(".audio")[0].playbackRate = Number(JSON.parse(voiceSpeed) / 100).toFixed(2);
                                    // $(".audio")[0].playbackRate = 1;
                                }
                                console.log("速度为："+$(".audio")[0].playbackRate);
                                $(".audio").on("playing",function () {
                                    status = false;//正在播放
                                    console.log("正在播放");
                                })
                                $(".audio").on("ended",function () {
                                    console.log("播放完毕");
                                    this.remove();
                                    audio = "";
                                    callList.splice(index,1);
                                    console.log(callList);
                                    status = true;
                                    call(callList,0);
                                })
                            // },100)
                            // 
                        }
                    }
                    if(status){
                        setTimeout(()=>{
                            call(callList,0);
                        },1000)
                    }
                    console.log(callList)
                }
            }
            // }else if(res.source === "REWARD"){
            //     if ( res.count > 0 ) {
            //         let unit;
            //         switch (res.productName) {
            //             case "玫瑰花":
            //             unit="朵";
            //             break;
            //             case "跑车":
            //             unit="辆";
            //             break;
            //             case "别墅":
            //             unit="栋";
            //             break;
            //             case "游艇":
            //             unit="只";
            //             break;
            //             case "水晶鞋":
            //             unit="双";
            //             break;
            //             default:
            //             unit="个";
            //             break;
            //         }
            //         let audio = '<audio style="display:none;" controls="" class="audio" src="'+API_BASE_URL+'v1/pos/speech?tex='+res.tableNum+'号客户机给'+res.empCode+'号服务员打赏'+res.qty+''+unit+''+res.productName+'&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="audios"></audio>';
            //         $('.App').append(audio);
            //     }
            // }
            
        });
    });
    this.stompClient.ws.onclose = function ( evnt ) {
        setTimeout(()=>{
            that.connect(that.state.storeId); 
        }, 1000);
    }
    this.stompClient.debug = function(str) {
        // console.log(str);
    };
  }
  componentDidCatch(error, info) {
    this.setState({ error, info });
    console.log(info);
  }
}

const mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators(actions, dispatch)
    }
}

export default withRouter(connect(
    (state)=>({wsStatus:state.wsData}),
    mapDispatchToProps
)(App));
